//
//  AppDelegate.swift
//  PushNotification
//
//  Created by ZHY on 2017/5/19.
//  Copyright © 2017年 ZHY. All rights reserved.
//

import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        
        
        
        RCIM.shared().initWithAppKey("sfci50a7sobki")
        RCIM.shared().connect(withToken: "TKQEH1en30dV7Cq5cb06oDljrBhqy/DnuSKv5EoEkhldxaU24txX7nqsxv2xxs85XKFR8gAftHuYtkUy43aA0w==", success: { (userId) in
            print("connnect success")
            DispatchQueue.main.async {
                let list = ChatListViewController()
                let nav = UINavigationController.init(rootViewController: list)
                self.window?.rootViewController = nav
                //注册消息推送通知
                self.registerNotification(application: application)
            }
        }, error: { (errorCode) in
            print("errorCode:\(errorCode)")
        }) {
            print("token错误")
        }
        
        self.window?.backgroundColor = UIColor.white
        return true
    }
    
    //注册消息推送通知
    func registerNotification(application:UIApplication) {
        
        if #available(iOS 10.0, *) {
            
            let center = UNUserNotificationCenter.current()
            center.requestAuthorization(options: [.badge,.sound,.alert], completionHandler: { (granted:Bool, error:Error?) in
                if error == nil {
                    print("request authorization success")
                    application.registerForRemoteNotifications()
                }
            })
        }else if #available(iOS 8.0, *) {
            let setting = UIUserNotificationSettings.init(types: [.badge,.sound,.alert], categories: nil)
            application.registerUserNotificationSettings(setting)
        }else {
            UIApplication.shared.registerForRemoteNotifications(matching: [.badge,.sound,.alert])
        }
    }
    
    //apns 在ios8系统中，还需要添加这个方法，通过新的api注册推送服务
    func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
        application.registerForRemoteNotifications()
    }
    
    //apns 获取DeviceToken
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        
        let data = NSData.init(data: deviceToken)
        let token = data.description.replacingOccurrences(of: "<", with: "").replacingOccurrences(of: ">", with: "").replacingOccurrences(of: " ", with: "")
        RCIMClient.shared().setDeviceToken(token)
    }

    //apns error
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("didFailToRegisterForRemoteNotificationsWithError:\(error)")
    }
    //apns iOS10有了新的收取推送通知的方法，我们便在此方法里处理服务器推送过来的数据userInfo，和处理跳转事件
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        print("userInfo:\(userInfo)")
        completionHandler(UIBackgroundFetchResult.newData)
    }
    
    
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

